/* USER CODE BEGIN Header */
/**
  ******************************************************************************
  * @file           : main.c
  * @brief          : Main program body
  ******************************************************************************
  * @attention
  *
  * Copyright (c) 2023 STMicroelectronics.
  * All rights reserved.
  *
  * This software is licensed under terms that can be found in the LICENSE file
  * in the root directory of this software component.
  * If no LICENSE file comes with this software, it is provided AS-IS.
  *
  ******************************************************************************
  */
/* USER CODE END Header */
/* Includes ------------------------------------------------------------------*/
#include "main.h"
#include "adc.h"
#include "dma.h"
#include "tim.h"
#include "usart.h"
#include "gpio.h"

/* Private includes ----------------------------------------------------------*/
/* USER CODE BEGIN Includes */
#include  "RGB.h"
#include "oled.h"
//#include "stdio.h"
#include "arm_math.h"
//#include "oledfont.h"
/* USER CODE END Includes */

/* Private typedef -----------------------------------------------------------*/
/* USER CODE BEGIN PTD */

/* USER CODE END PTD */

/* Private define ------------------------------------------------------------*/
/* USER CODE BEGIN PD */
typedef enum //枚举
{
KEY_CHECK = 0, //键盘�??????????????????????测状�??????????????????????
KEY_COMFIRM, //键盘确认状�??
KEY_RELEASE //键盘释放状�??
} KEY_STATE;
/* USER CODE END PD */

/* Private macro -------------------------------------------------------------*/
/* USER CODE BEGIN PM */
//int fputc(int ch, FILE *f)
//{
//  HAL_UART_Transmit(&huart1, (uint8_t *)&ch, 1, 0xffff);
//  return ch;
//}

/* USER CODE END PM */

/* Private variables ---------------------------------------------------------*/

/* USER CODE BEGIN PV */
float  ad1 =0;
uint32_t ADC_Value[2049];
float ADC_Value_1[2049];
float max_adc=-100;
float min_adc=9999;
float vpp=0;
int adc_dma_ok=0;
int print_flag=0;
int last_av=0;
uint32_t detected[10]={0};//to detect the zero point
int detect_points=0;
float period=0;
int last_max=0;
int current_array=0;
float vrms=0.0;
uint32_t max_index=0;
int key1=0;
KEY_STATE key1_state=KEY_CHECK;
/* USER CODE END PV */

/* Private function prototypes -----------------------------------------------*/
void SystemClock_Config(void);
/* USER CODE BEGIN PFP */
void HAL_ADC_ConvCpltCallback(ADC_HandleTypeDef* hadc)
{
  if(hadc==&hadc1)
  //if(0)
  {
    //HAL_ADC_Stop_DMA(&hadc1);
    max_adc=0;
    min_adc=9999;
    detect_points=0;
    int up_flag=0;
    int down_flag=0;
    period=0;
    for(int i = 50; i < 2000; i++)//数据处理 �?????? DMA 存�?�不同步
    {
			ADC_Value_1[i-50]=ADC_Value[i]*3.3/4096;
      //ad1 += ADC_Value[i]; 
      // if(ADC_Value[i]>max_adc)
      //   max_adc=ADC_Value[i];
      // if(ADC_Value[i]<min_adc)
      //   min_adc=ADC_Value[i];
      if(ADC_Value[i]>(last_av)&&ADC_Value[i-1]<=last_av)//过零�?????�?????
      {
        if(up_flag==0)
        {
          up_flag=1;
          if(detect_points<2)
          {
            detected[detect_points]=i;
            detect_points++;
          }
        }
      }
      else
      {
        up_flag=0;
      }
    } 
    if(detect_points<2)
    {
      period=0;
    }
    else
    {
      //for(int i=1;i<detect_points;i++)
      {
        period=detected[1]-detected[0];
      }
      //period/=(detect_points-1)*1.0;
    }
    arm_max_f32(ADC_Value_1,1950,&max_adc,&max_index);
    arm_min_f32(ADC_Value_1,1950,&min_adc,&max_index);
		arm_rms_f32(ADC_Value_1,1950,&vrms);
    arm_mean_f32(ADC_Value_1,1950,&ad1);
    //ad1 /= 1950.0;
    last_av=ad1/3.3*4096;
    //ad1*=3.3f/4096;
    vpp=max_adc-min_adc;
    //vpp*=3.3/4096;
    //last_max=max_adc;
    adc_dma_ok=1;    
    //HAL_Delay(1000);
    HAL_ADC_Start_DMA(&hadc1,ADC_Value, 2048);
  }
  //adc_dma_ok=1;
}
/* USER CODE END PFP */

/* Private user code ---------------------------------------------------------*/
/* USER CODE BEGIN 0 */
void updatepinstate(KEY_STATE *key,GPIO_TypeDef *port,uint16_t pin,int *keyflag)//单按键消抖状态机
{
  switch (*key)
  {
    case KEY_CHECK:
      if (HAL_GPIO_ReadPin(port,pin)== 0)
      {
        *key = KEY_COMFIRM;
      }
      break;
    case KEY_COMFIRM:
    {
      if (HAL_GPIO_ReadPin(port,pin)== 0)
      {
        *key = KEY_RELEASE;
        *keyflag = 1;
      }
      else
      {
        *key = KEY_CHECK;
      }
      break;
    }
    case KEY_RELEASE:
      if (HAL_GPIO_ReadPin(port,pin)== 1)
      {
        *key = KEY_CHECK;
      }
    break;
  }
}
void HAL_TIM_PeriodElapsedCallback(TIM_HandleTypeDef *htim)
{
  if(htim->Instance==htim10.Instance)
  {
    updatepinstate(&key1_state,KEY_1_GPIO_Port,KEY_1_Pin,&key1);
  }
}
/* USER CODE END 0 */

/**
  * @brief  The application entry point.
  * @retval int
  */
int main(void)
{
  /* USER CODE BEGIN 1 */

  /* USER CODE END 1 */

  /* MCU Configuration--------------------------------------------------------*/

  /* Reset of all peripherals, Initializes the Flash interface and the Systick. */
  HAL_Init();

  /* USER CODE BEGIN Init */

  /* USER CODE END Init */

  /* Configure the system clock */
  SystemClock_Config();

  /* USER CODE BEGIN SysInit */

  /* USER CODE END SysInit */

  /* Initialize all configured peripherals */
  MX_GPIO_Init();
  MX_DMA_Init();
  MX_TIM2_Init();
  MX_ADC1_Init();
  MX_USART1_UART_Init();
  MX_TIM10_Init();
  /* USER CODE BEGIN 2 */
  HAL_TIM_Base_Start_IT(&htim10);
  RGB_BLUE(3);
  HAL_Delay(1000);
  RGB_RED(3);
  OLED_Init();
  OLED_Clear();
  OLED_ShowString(0,0,"Hello World");
  OLED_Clear();
  OLED_ShowString(0,0,"vpp:");
  OLED_ShowString(0,2,"av:");
  OLED_ShowString(0,4,"f:");
  OLED_ShowString(0,6,"vrms:");
  /* USER CODE END 2 */

  /* Infinite loop */
  /* USER CODE BEGIN WHILE */
  HAL_ADC_Start_DMA(&hadc1,ADC_Value, 2048);
  int test_key=0;
  //HAL_ADC_Start_DMA(&hadc1,ADC_Value, 2048);
  //HAL_ADC_Start_DMA(&hadc1,ADC_Value, 2048);
  while (1)
  {
    /* USER CODE END WHILE */

    /* USER CODE BEGIN 3 */
    if(key1)
    {
      test_key++;
      key1=0;
    }
    // if(print_flag<30)
    //   print_flag++;
    // else
    // {
    //   if(print_flag==30&&adc_dma_ok==1)
    //         {
    //           HAL_ADC_Stop_DMA(&hadc1);
    //           for(int i=0;i<2048;i++)
    //           {
    //             printf("%d\n",ADC_Value[i]);
    //             HAL_Delay(1);
    //           }
    //           printf("av:%d\n",last_av);
    //           print_flag=66;
    //           HAL_ADC_Start_DMA(&hadc1,ADC_Value, 2048);
    //         }
    // }
    

     
      //printf("ADC1 Reading : %d \r\n",ad1);//采样的�??
      //printf("True Voltage value : %.4f \r\n",ad1*3.3f/4096);//转化后的电压�??????
      if(adc_dma_ok==1)
      {

        // for(int i=0;i<1024;i++)
        // {
        //   printf("%d,%d\n",ADC_Value[i],last_av);
        //   HAL_Delay(1);
        // }
        //printf("av:%d\n",last_av);
        //OLED_Clear();
        //OLED_ShowString(50,4,"   ");
        OLED_Show_float(50,0,vpp);
        OLED_Show_float(50,2,ad1);
        OLED_Show_float(50,4,1/(period/700));
        OLED_Show_float(50,6,vrms);
        adc_dma_ok=0;
        //HAL_ADC_Start_DMA(&hadc1,ADC_Value, 2048);
      }
      //OLED_Show_float(50,6,test_key);
      HAL_Delay(100);
    

  }
  /* USER CODE END 3 */
}

/**
  * @brief System Clock Configuration
  * @retval None
  */
void SystemClock_Config(void)
{
  RCC_OscInitTypeDef RCC_OscInitStruct = {0};
  RCC_ClkInitTypeDef RCC_ClkInitStruct = {0};

  /** Configure the main internal regulator output voltage
  */
  __HAL_RCC_PWR_CLK_ENABLE();
  __HAL_PWR_VOLTAGESCALING_CONFIG(PWR_REGULATOR_VOLTAGE_SCALE2);

  /** Initializes the RCC Oscillators according to the specified parameters
  * in the RCC_OscInitTypeDef structure.
  */
  RCC_OscInitStruct.OscillatorType = RCC_OSCILLATORTYPE_HSE;
  RCC_OscInitStruct.HSEState = RCC_HSE_ON;
  RCC_OscInitStruct.PLL.PLLState = RCC_PLL_ON;
  RCC_OscInitStruct.PLL.PLLSource = RCC_PLLSOURCE_HSE;
  RCC_OscInitStruct.PLL.PLLM = 25;
  RCC_OscInitStruct.PLL.PLLN = 168;
  RCC_OscInitStruct.PLL.PLLP = RCC_PLLP_DIV2;
  RCC_OscInitStruct.PLL.PLLQ = 4;
  if (HAL_RCC_OscConfig(&RCC_OscInitStruct) != HAL_OK)
  {
    Error_Handler();
  }

  /** Initializes the CPU, AHB and APB buses clocks
  */
  RCC_ClkInitStruct.ClockType = RCC_CLOCKTYPE_HCLK|RCC_CLOCKTYPE_SYSCLK
                              |RCC_CLOCKTYPE_PCLK1|RCC_CLOCKTYPE_PCLK2;
  RCC_ClkInitStruct.SYSCLKSource = RCC_SYSCLKSOURCE_PLLCLK;
  RCC_ClkInitStruct.AHBCLKDivider = RCC_SYSCLK_DIV1;
  RCC_ClkInitStruct.APB1CLKDivider = RCC_HCLK_DIV2;
  RCC_ClkInitStruct.APB2CLKDivider = RCC_HCLK_DIV1;

  if (HAL_RCC_ClockConfig(&RCC_ClkInitStruct, FLASH_LATENCY_2) != HAL_OK)
  {
    Error_Handler();
  }
}

/* USER CODE BEGIN 4 */

/* USER CODE END 4 */

/**
  * @brief  This function is executed in case of error occurrence.
  * @retval None
  */
void Error_Handler(void)
{
  /* USER CODE BEGIN Error_Handler_Debug */
  /* User can add his own implementation to report the HAL error return state */
  __disable_irq();
  while (1)
  {
  }
  /* USER CODE END Error_Handler_Debug */
}

#ifdef  USE_FULL_ASSERT
/**
  * @brief  Reports the name of the source file and the source line number
  *         where the assert_param error has occurred.
  * @param  file: pointer to the source file name
  * @param  line: assert_param error line source number
  * @retval None
  */
void assert_failed(uint8_t *file, uint32_t line)
{
  /* USER CODE BEGIN 6 */
  /* User can add his own implementation to report the file name and line number,
     ex: printf("Wrong parameters value: file %s on line %d\r\n", file, line) */
  /* USER CODE END 6 */
}
#endif /* USE_FULL_ASSERT */
